<template>
  <div>
    <!-- show-checkbox: tree 显示复选框 -->
    <!-- check-strictly: 父子节点不关联 -->
    <!-- 如果需要通过 Key 获取已勾选的节点内容, 需要设置 node-key -->
    <!-- 获取已勾选的 Keys, 调用 this.$refs.tree.getCheckedKeys() -->
    <el-tree
      ref="tree"
      node-key="id"
      show-checkbox
      check-strictly
      default-expand-all
      :data="permissions"
      :props="{ label: 'name' }"
    />

    <div class="footer">
      <el-button size="mini" @click="$emit('close')">取消</el-button>
      <el-button type="primary" size="mini" @click="hSubmit">确定</el-button>
    </div>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils'
import { assignPermission, getRoleDetail } from '@/api/setting'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissions: []
    }
  },
  created() {
    this.loadPermissions()
    this.loadRoleDetail()
  },
  methods: {
    // 发请求获取权限列表
    async loadPermissions() {
      try {
        const res = await getPermissionList()
        // console.log(res) 转换并且复制
        this.permissions = tranListToTreeData(res.data)
      } catch (e) {
        console.log(e)
      }
    },
    async hSubmit() {
      try {
        const ids = this.$refs.tree.getCheckedKeys()
        // console.log(ids)
        const res = await assignPermission({ id: this.id, permIds: ids })
        // 提醒用户
        this.$message.success(res.message)
        // 关闭弹框
        this.$emit('close')
      } catch (e) {
        this.$message.success(e.message)
      }
    },
    async loadRoleDetail() {
      try {
        // 发请求
        const res = await getRoleDetail(this.id)
        // 数据回填
        this.$refs.tree.setCheckedKeys(res.data.permIds)
      } catch (e) {
        console.log(e)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.footer {
  display: flex;
  justify-content:flex-end;
}
</style>
